// 地图编辑器核心功能
class MapEditor {
    constructor() {
        this.canvas = document.getElementById('mapCanvas');
        this.ctx = this.canvas.getContext('2d');
        
        // 编辑器状态
        this.state = {
            currentMode: 'normal', // normal, duel, boss
            currentTool: 'place', // place, erase, select, move
            selectedElement: 'obstacle', // obstacle, spawn, respawn, special1, special2, boss
            zoomLevel: 1.0,
            gridSize: 20,
            mapWidth: 1200,
            mapHeight: 1200,
            offsetX: 0,
            offsetY: 0,
            isDragging: false,
            isPlacing: false,
            isErasing: false,
            lastMouseX: 0,
            lastMouseY: 0,
            lastPlacedX: 0,
            lastPlacedY: 0,
            lastErasedX: 0,
            lastErasedY: 0,
            brushSize: 1 // 画笔大小，1表示1x1，3表示3x3，以此类推
        };
        
        // 地图数据
        this.mapData = {
            obstacles: [],
            spawnPoints: [],
            respawnPoints: [],
            specialPoints: [],
            bossPoints: []
        };
        
        // 历史记录（用于撤回功能）
        this.history = [];
        this.historyIndex = -1;
        
        // 初始化
        this.init();
    }
    
    init() {
        this.setupCanvas();
        this.setupEventListeners();
        this.setupUI();
        this.render();
    }
    
    setupCanvas() {
        // 设置画布尺寸 - 使用HTML中定义的尺寸
        this.canvas.width = 1200;
        this.canvas.height = 1200;
        
        // 设置初始缩放和偏移
        this.updateCanvasTransform();
    }
    
    setupEventListeners() {
        // 鼠标事件
        this.canvas.addEventListener('mousedown', this.handleMouseDown.bind(this));
        this.canvas.addEventListener('mousemove', this.handleMouseMove.bind(this));
        this.canvas.addEventListener('mouseup', this.handleMouseUp.bind(this));
        this.canvas.addEventListener('wheel', this.handleWheel.bind(this));
        
        // 键盘事件
        document.addEventListener('keydown', this.handleKeyDown.bind(this));
        
        // 窗口大小变化
        window.addEventListener('resize', this.handleResize.bind(this));
    }
    
    setupUI() {
        // 模式选择
        document.querySelectorAll('.mode-option').forEach(option => {
            option.addEventListener('click', (e) => {
                this.selectMode(e.currentTarget.dataset.mode);
            });
        });
        
        // 地图设置
        document.getElementById('mapWidth').addEventListener('change', (e) => {
            this.state.mapWidth = parseInt(e.target.value);
            this.updateMapSize();
        });
        
        document.getElementById('mapHeight').addEventListener('change', (e) => {
            this.state.mapHeight = parseInt(e.target.value);
            this.updateMapSize();
        });
        
        // 元素选择
        document.querySelectorAll('.element-item').forEach(item => {
            item.addEventListener('click', (e) => {
                this.selectElement(e.currentTarget.dataset.element);
            });
        });
        
        // 工具选择
        document.querySelectorAll('.tool-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                this.selectTool(e.currentTarget.dataset.tool);
            });
        });
        
        // 缩放控制
        document.getElementById('zoomIn').addEventListener('click', () => {
            this.zoomIn();
        });
        
        document.getElementById('zoomOut').addEventListener('click', () => {
            this.zoomOut();
        });
        
        document.getElementById('zoomReset').addEventListener('click', () => {
            this.zoomReset();
        });
        
        // 控制按钮
        document.getElementById('saveBtn').addEventListener('click', () => {
            this.saveMap();
        });
        
        document.getElementById('exportBtn').addEventListener('click', () => {
            this.exportMap();
        });
        
        document.getElementById('clearBtn').addEventListener('click', () => {
            this.clearMap();
        });
        
        document.getElementById('clearAllBtn').addEventListener('click', () => {
            this.clearAll();
        });
        
        document.getElementById('backBtn').addEventListener('click', () => {
            this.goBack();
        });
        
        document.getElementById('undoBtn').addEventListener('click', () => {
            this.undo();
        });
        
        document.getElementById('redoBtn').addEventListener('click', () => {
            this.redo();
        });
        
        // 画笔大小选择
        document.querySelectorAll('.brush-size-option').forEach(option => {
            option.addEventListener('click', (e) => {
                this.selectBrushSize(parseInt(e.currentTarget.dataset.size));
            });
        });
    }
    
    // 模式选择
    selectMode(mode) {
        this.state.currentMode = mode;
        
        // 更新UI
        document.querySelectorAll('.mode-option').forEach(option => {
            option.classList.remove('active');
        });
        document.querySelector(`[data-mode="${mode}"]`).classList.add('active');
        
        // 根据模式启用/禁用元素
        this.updateElementAvailability();
        
        this.render();
    }
    
    // 更新元素可用性
    updateElementAvailability() {
        const elements = document.querySelectorAll('.element-item');
        elements.forEach(element => {
            const type = element.dataset.element;
            
            switch (this.state.currentMode) {
                case 'normal':
                    element.classList.toggle('disabled', type !== 'obstacle');
                    break;
                case 'duel':
                    element.classList.toggle('disabled', 
                        type !== 'obstacle' && type !== 'spawn' && type !== 'respawn' && !type.startsWith('special')
                    );
                    break;
                case 'boss':
                    element.classList.toggle('disabled', 
                        type !== 'obstacle' && type !== 'boss' && !type.startsWith('special')
                    );
                    break;
            }
        });
    }
    
    // 元素选择
    selectElement(element) {
        if (document.querySelector(`[data-element="${element}"]`).classList.contains('disabled')) {
            return;
        }
        
        this.state.selectedElement = element;
        
        // 更新UI
        document.querySelectorAll('.element-item').forEach(item => {
            item.classList.remove('active');
        });
        document.querySelector(`[data-element="${element}"]`).classList.add('active');
        
        this.render();
    }
    
    // 画笔大小选择
    selectBrushSize(size) {
        this.state.brushSize = size;
        
        // 更新UI
        document.querySelectorAll('.brush-size-option').forEach(option => {
            option.classList.remove('active');
        });
        document.querySelector(`[data-size="${size}"]`).classList.add('active');
        
        this.render();
    }
    
    // 工具选择
    selectTool(tool) {
        this.state.currentTool = tool;
        
        // 更新UI
        document.querySelectorAll('.tool-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        document.querySelector(`[data-tool="${tool}"]`).classList.add('active');
        
        // 更新光标
        this.updateCursor();
    }
    
    // 更新光标样式
    updateCursor() {
        switch (this.state.currentTool) {
            case 'place':
                this.canvas.style.cursor = 'crosshair';
                break;
            case 'erase':
                this.canvas.style.cursor = 'crosshair';
                break;
            case 'select':
                this.canvas.style.cursor = 'pointer';
                break;
            case 'move':
                this.canvas.style.cursor = 'move';
                break;
        }
    }
    
    // 缩放功能
    zoomIn() {
        this.state.zoomLevel = Math.min(this.state.zoomLevel * 1.2, 5.0);
        this.updateZoomDisplay();
        this.render();
    }
    
    zoomOut() {
        this.state.zoomLevel = Math.max(this.state.zoomLevel / 1.2, 0.2);
        this.updateZoomDisplay();
        this.render();
    }
    
    zoomReset() {
        this.state.zoomLevel = 1.0;
        this.updateZoomDisplay();
        this.render();
    }
    
    updateZoomDisplay() {
        document.getElementById('zoomLevel').textContent = 
            Math.round(this.state.zoomLevel * 100) + '%';
    }
    
    // 鼠标事件处理
    handleMouseDown(e) {
        const rect = this.canvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        const worldPos = this.screenToWorld(x, y);
        
        switch (this.state.currentTool) {
            case 'place':
                this.placeElement(worldPos.x, worldPos.y);
                this.state.isPlacing = true;
                this.state.lastPlacedX = worldPos.x;
                this.state.lastPlacedY = worldPos.y;
                break;
            case 'erase':
                this.eraseElement(worldPos.x, worldPos.y);
                this.state.isErasing = true;
                this.state.lastErasedX = worldPos.x;
                this.state.lastErasedY = worldPos.y;
                break;
            case 'move':
                this.state.isDragging = true;
                this.state.lastMouseX = e.clientX;
                this.state.lastMouseY = e.clientY;
                break;
        }
        
        this.render();
    }
    
    handleMouseMove(e) {
        const rect = this.canvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        const worldPos = this.screenToWorld(x, y);
        
        // 更新坐标显示
        this.updateCoordinates(worldPos.x, worldPos.y);
        
        if (this.state.isDragging) {
            const deltaX = e.clientX - this.state.lastMouseX;
            const deltaY = e.clientY - this.state.lastMouseY;
            
            this.state.offsetX -= deltaX / this.state.zoomLevel;
            this.state.offsetY -= deltaY / this.state.zoomLevel;
            
            this.state.lastMouseX = e.clientX;
            this.state.lastMouseY = e.clientY;
            
            this.render();
        } else if (this.state.isPlacing && this.state.currentTool === 'place') {
            // 连续放置功能：当鼠标移动且按住左键时，在新位置放置元素
            if (worldPos.x !== this.state.lastPlacedX || worldPos.y !== this.state.lastPlacedY) {
                this.placeElement(worldPos.x, worldPos.y);
                this.state.lastPlacedX = worldPos.x;
                this.state.lastPlacedY = worldPos.y;
                this.render();
            }
        } else if (this.state.isErasing && this.state.currentTool === 'erase') {
            // 连续擦除功能：当鼠标移动且按住左键时，在新位置擦除元素
            if (worldPos.x !== this.state.lastErasedX || worldPos.y !== this.state.lastErasedY) {
                this.eraseElement(worldPos.x, worldPos.y);
                this.state.lastErasedX = worldPos.x;
                this.state.lastErasedY = worldPos.y;
                this.render();
            }
        }
    }
    
    handleMouseUp(e) {
        this.state.isDragging = false;
        this.state.isPlacing = false;
        this.state.isErasing = false;
    }
    
    handleWheel(e) {
        e.preventDefault();
        
        const rect = this.canvas.getBoundingClientRect();
        const mouseX = e.clientX - rect.left;
        const mouseY = e.clientY - rect.top;
        
        const zoomFactor = e.deltaY > 0 ? 0.9 : 1.1;
        const oldZoom = this.state.zoomLevel;
        this.state.zoomLevel = Math.max(0.2, Math.min(5.0, this.state.zoomLevel * zoomFactor));
        
        // 调整偏移以保持鼠标位置
        const worldPos = this.screenToWorld(mouseX, mouseY);
        this.state.offsetX += (mouseX / oldZoom - mouseX / this.state.zoomLevel);
        this.state.offsetY += (mouseY / oldZoom - mouseY / this.state.zoomLevel);
        
        this.updateZoomDisplay();
        this.render();
    }
    
    // 键盘事件处理
    handleKeyDown(e) {
        switch (e.key) {
            case 'z':
                if (e.ctrlKey || e.metaKey) {
                    e.preventDefault();
                    this.undo();
                }
                break;
            case 'y':
                if (e.ctrlKey || e.metaKey) {
                    e.preventDefault();
                    this.redo();
                }
                break;
            case '=':
            case '+':
                e.preventDefault();
                this.zoomIn();
                break;
            case '-':
                e.preventDefault();
                this.zoomOut();
                break;
            case '0':
                e.preventDefault();
                this.zoomReset();
                break;
        }
    }
    
    // 窗口大小变化处理
    handleResize() {
        this.render();
    }
    
    // 坐标转换
    screenToWorld(screenX, screenY) {
        return {
            x: Math.floor((screenX / this.state.zoomLevel + this.state.offsetX) / this.state.gridSize) * this.state.gridSize,
            y: Math.floor((screenY / this.state.zoomLevel + this.state.offsetY) / this.state.gridSize) * this.state.gridSize
        };
    }
    
    worldToScreen(worldX, worldY) {
        return {
            x: (worldX - this.state.offsetX) * this.state.zoomLevel,
            y: (worldY - this.state.offsetY) * this.state.zoomLevel
        };
    }
    
    // 放置元素
    placeElement(x, y) {
        // 检查边界
        if (x < 0 || x >= this.state.mapWidth || y < 0 || y >= this.state.mapHeight) {
            return;
        }
        
        // 保存历史状态
        this.saveHistory();
        
        // 根据画笔大小放置元素
        if (this.state.brushSize === 1) {
            // 单个放置
            this.placeSingleElement(x, y);
        } else {
            // 画笔大小放置（以当前位置为中心的方形区域）
            this.placeBrushElements(x, y);
        }
        
        this.updateStatus();
    }
    
    // 放置单个元素
    placeSingleElement(x, y) {
        const element = {
            x: x,
            y: y,
            type: this.state.selectedElement
        };
        
        // 根据元素类型添加到对应数组
        this.addElementToArray(element);
    }
    
    // 放置画笔大小区域内的元素
    placeBrushElements(centerX, centerY) {
        const brushSize = this.state.brushSize;
        const halfSize = Math.floor(brushSize / 2);
        
        for (let dx = -halfSize; dx <= halfSize; dx++) {
            for (let dy = -halfSize; dy <= halfSize; dy++) {
                const x = centerX + dx * this.state.gridSize;
                const y = centerY + dy * this.state.gridSize;
                
                // 检查边界
                if (x >= 0 && x < this.state.mapWidth && y >= 0 && y < this.state.mapHeight) {
                    this.placeSingleElement(x, y);
                }
            }
        }
    }
    
    // 添加元素到对应数组
    addElementToArray(element) {
        // 检查是否已存在相同位置的元素（避免重复放置）
        const existingElement = this.findElementAtPosition(element.x, element.y);
        if (existingElement) {
            return; // 位置已有元素，不重复放置
        }
        
        // 根据元素类型添加到对应数组
        switch (this.state.selectedElement) {
            case 'obstacle':
                this.mapData.obstacles.push(element);
                break;
            case 'spawn':
                this.mapData.spawnPoints.push(element);
                break;
            case 'respawn':
                this.mapData.respawnPoints.push(element);
                break;
            case 'special1':
            case 'special2':
            case 'special3':
                this.mapData.specialPoints.push(element);
                break;
            case 'boss':
                this.mapData.bossPoints.push(element);
                break;
        }
    }
    
    // 查找指定位置的元素
    findElementAtPosition(x, y) {
        const tolerance = this.state.gridSize / 2;
        
        // 检查所有元素类型
        const arrays = [
            this.mapData.obstacles,
            this.mapData.spawnPoints,
            this.mapData.respawnPoints,
            this.mapData.specialPoints,
            this.mapData.bossPoints
        ];
        
        for (const array of arrays) {
            for (const element of array) {
                const distance = Math.sqrt(Math.pow(element.x - x, 2) + Math.pow(element.y - y, 2));
                if (distance <= tolerance) {
                    return element;
                }
            }
        }
        
        return null;
    }
    
    // 擦除元素
    eraseElement(x, y) {
        // 保存历史状态
        this.saveHistory();
        
        // 根据画笔大小擦除元素
        if (this.state.brushSize === 1) {
            // 单个擦除
            this.eraseSingleElement(x, y);
        } else {
            // 画笔大小擦除（以当前位置为中心的方形区域）
            this.eraseBrushElements(x, y);
        }
        
        this.updateStatus();
    }
    
    // 擦除单个元素
    eraseSingleElement(x, y) {
        const tolerance = this.state.gridSize / 2;
        
        // 检查所有元素类型并删除
        const arrays = [
            this.mapData.obstacles,
            this.mapData.spawnPoints,
            this.mapData.respawnPoints,
            this.mapData.specialPoints,
            this.mapData.bossPoints
        ];
        
        arrays.forEach(array => {
            for (let i = array.length - 1; i >= 0; i--) {
                const element = array[i];
                const distance = Math.sqrt(Math.pow(element.x - x, 2) + Math.pow(element.y - y, 2));
                
                if (distance <= tolerance) {
                    array.splice(i, 1);
                    break;
                }
            }
        });
    }
    
    // 擦除画笔大小区域内的元素
    eraseBrushElements(centerX, centerY) {
        const brushSize = this.state.brushSize;
        const halfSize = Math.floor(brushSize / 2);
        
        for (let dx = -halfSize; dx <= halfSize; dx++) {
            for (let dy = -halfSize; dy <= halfSize; dy++) {
                const x = centerX + dx * this.state.gridSize;
                const y = centerY + dy * this.state.gridSize;
                
                // 检查边界
                if (x >= 0 && x < this.state.mapWidth && y >= 0 && y < this.state.mapHeight) {
                    this.eraseSingleElement(x, y);
                }
            }
        }
    }
    
    // 更新状态栏
    updateStatus() {
        document.getElementById('elementCount').textContent = 
            this.mapData.obstacles.length + this.mapData.spawnPoints.length + 
            this.mapData.respawnPoints.length + this.mapData.specialPoints.length + 
            this.mapData.bossPoints.length;
        
        document.getElementById('mapSize').textContent = 
            `${this.state.mapWidth} × ${this.state.mapHeight}`;
    }
    
    // 更新坐标显示
    updateCoordinates(x, y) {
        document.getElementById('coordinateDisplay').textContent = 
            `坐标: (${Math.round(x)}, ${Math.round(y)})`;
    }
    
    // 更新画布变换
    updateCanvasTransform() {
        this.ctx.setTransform(this.state.zoomLevel, 0, 0, this.state.zoomLevel, 
                             -this.state.offsetX * this.state.zoomLevel, 
                             -this.state.offsetY * this.state.zoomLevel);
    }
    
    // 渲染函数
    render() {
        this.ctx.save();
        
        // 清除画布
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 更新变换
        this.updateCanvasTransform();
        
        // 绘制网格
        this.drawGrid();
        
        // 绘制边界
        this.drawBoundaries();
        
        // 绘制元素
        this.drawElements();
        
        this.ctx.restore();
    }
    
    // 绘制网格
    drawGrid() {
        const gridSize = this.state.gridSize;
        const width = this.state.mapWidth;
        const height = this.state.mapHeight;
        
        this.ctx.strokeStyle = '#bdc3c7';
        this.ctx.lineWidth = 1;
        
        // 绘制垂直线
        for (let x = 0; x <= width; x += gridSize) {
            this.ctx.beginPath();
            this.ctx.moveTo(x, 0);
            this.ctx.lineTo(x, height);
            this.ctx.stroke();
        }
        
        // 绘制水平线
        for (let y = 0; y <= height; y += gridSize) {
            this.ctx.beginPath();
            this.ctx.moveTo(0, y);
            this.ctx.lineTo(width, y);
            this.ctx.stroke();
        }
        
        // 绘制主要网格线
        this.ctx.strokeStyle = '#95a5a6';
        this.ctx.lineWidth = 2;
        
        for (let x = 0; x <= width; x += gridSize * 5) {
            this.ctx.beginPath();
            this.ctx.moveTo(x, 0);
            this.ctx.lineTo(x, height);
            this.ctx.stroke();
        }
        
        for (let y = 0; y <= height; y += gridSize * 5) {
            this.ctx.beginPath();
            this.ctx.moveTo(0, y);
            this.ctx.lineTo(width, y);
            this.ctx.stroke();
        }
    }
    
    // 绘制边界
    drawBoundaries() {
        const width = this.state.mapWidth;
        const height = this.state.mapHeight;
        
        this.ctx.strokeStyle = '#e74c3c';
        this.ctx.lineWidth = 3;
        this.ctx.strokeRect(0, 0, width, height);
    }
    
    // 绘制元素
    drawElements() {
        // 绘制障碍物
        this.mapData.obstacles.forEach(obstacle => {
            this.drawObstacle(obstacle.x, obstacle.y);
        });
        
        // 绘制生成点
        this.mapData.spawnPoints.forEach(spawn => {
            this.drawSpawnPoint(spawn.x, spawn.y);
        });
        
        // 绘制复活点
        this.mapData.respawnPoints.forEach(respawn => {
            this.drawRespawnPoint(respawn.x, respawn.y);
        });
        
        // 绘制特殊点
        this.mapData.specialPoints.forEach(special => {
            this.drawSpecialPoint(special.x, special.y, special.type);
        });
        
        // 绘制Boss点
        this.mapData.bossPoints.forEach(boss => {
            this.drawBossPoint(boss.x, boss.y);
        });
    }
    
    // 绘制障碍物
    drawObstacle(x, y) {
        const size = this.state.gridSize;
        this.ctx.fillStyle = '#e74c3c';
        this.ctx.fillRect(x, y, size, size);
        this.ctx.strokeStyle = '#c0392b';
        this.ctx.lineWidth = 2;
        this.ctx.strokeRect(x, y, size, size);
    }
    
    // 绘制生成点
    drawSpawnPoint(x, y) {
        const size = this.state.gridSize;
        this.ctx.fillStyle = '#27ae60';
        this.ctx.beginPath();
        this.ctx.arc(x + size/2, y + size/2, size/2 - 2, 0, Math.PI * 2);
        this.ctx.fill();
        this.ctx.strokeStyle = '#219a52';
        this.ctx.lineWidth = 2;
        this.ctx.stroke();
    }
    
    // 绘制复活点
    drawRespawnPoint(x, y) {
        const size = this.state.gridSize;
        this.ctx.fillStyle = '#f39c12';
        this.ctx.beginPath();
        this.ctx.moveTo(x + size/2, y);
        this.ctx.lineTo(x + size, y + size);
        this.ctx.lineTo(x, y + size);
        this.ctx.closePath();
        this.ctx.fill();
        this.ctx.strokeStyle = '#e67e22';
        this.ctx.lineWidth = 2;
        this.ctx.stroke();
    }
    
    // 绘制特殊点
    drawSpecialPoint(x, y, type) {
        const size = this.state.gridSize;
        const colors = {
            'special1': '#9b59b6',
            'special2': '#3498db',
            'special3': '#1abc9c'
        };
        
        this.ctx.fillStyle = colors[type] || '#9b59b6';
        this.ctx.fillRect(x + 2, y + 2, size - 4, size - 4);
        this.ctx.strokeStyle = colors[type] ? colors[type].replace('8', '7') : '#8e44ad';
        this.ctx.lineWidth = 2;
        this.ctx.strokeRect(x + 2, y + 2, size - 4, size - 4);
    }
    
    // 绘制Boss点
    drawBossPoint(x, y) {
        const size = this.state.gridSize;
        this.ctx.fillStyle = '#c0392b';
        this.ctx.beginPath();
        this.ctx.arc(x + size/2, y + size/2, size/2 - 2, 0, Math.PI * 2);
        this.ctx.fill();
        
        // 绘制Boss图标
        this.ctx.fillStyle = '#ffffff';
        this.ctx.font = 'bold 12px Arial';
        this.ctx.textAlign = 'center';
        this.ctx.textBaseline = 'middle';
        this.ctx.fillText('B', x + size/2, y + size/2);
    }
    
    // 历史记录功能
    saveHistory() {
        // 只保留最近50个状态
        if (this.history.length > 50) {
            this.history.shift();
        }
        
        // 保存当前状态
        this.history.push(JSON.parse(JSON.stringify(this.mapData)));
        this.historyIndex = this.history.length - 1;
        
        this.updateUndoRedoButtons();
    }
    
    undo() {
        if (this.historyIndex > 0) {
            this.historyIndex--;
            this.mapData = JSON.parse(JSON.stringify(this.history[this.historyIndex]));
            this.render();
            this.updateStatus();
            this.updateUndoRedoButtons();
        }
    }
    
    redo() {
        if (this.historyIndex < this.history.length - 1) {
            this.historyIndex++;
            this.mapData = JSON.parse(JSON.stringify(this.history[this.historyIndex]));
            this.render();
            this.updateStatus();
            this.updateUndoRedoButtons();
        }
    }
    
    updateUndoRedoButtons() {
        document.getElementById('undoBtn').classList.toggle('disabled', this.historyIndex <= 0);
        document.getElementById('redoBtn').classList.toggle('disabled', this.historyIndex >= this.history.length - 1);
    }
    
    // 保存地图
    saveMap() {
        const mapData = {
            mode: this.state.currentMode,
            width: this.state.mapWidth,
            height: this.state.mapHeight,
            gridSize: this.state.gridSize,
            elements: this.mapData
        };
        
        localStorage.setItem('snakeMapEditor_data', JSON.stringify(mapData));
        this.showMessage('地图已保存到本地存储', 'success');
    }
    
    // 导出地图
    exportMap() {
        const mapData = {
            mode: this.state.currentMode,
            width: this.state.mapWidth,
            height: this.state.mapHeight,
            gridSize: this.state.gridSize,
            elements: this.mapData
        };
        
        const dataStr = JSON.stringify(mapData, null, 2);
        const dataBlob = new Blob([dataStr], {type: 'application/json'});
        
        const link = document.createElement('a');
        link.href = URL.createObjectURL(dataBlob);
        link.download = `snake_map_${this.state.currentMode}_${Date.now()}.json`;
        link.click();
        
        this.showMessage('地图已导出为JSON文件', 'success');
    }
    
    // 清空地图
    clearMap() {
        if (confirm('确定要清空当前地图吗？此操作不可撤销。')) {
            this.saveHistory();
            
            this.mapData = {
                obstacles: [],
                spawnPoints: [],
                respawnPoints: [],
                specialPoints: [],
                bossPoints: []
            };
            
            this.render();
            this.updateStatus();
            this.showMessage('地图已清空', 'info');
        }
    }
    
    // 擦除全屏
    clearAll() {
        if (confirm('确定要擦除全屏吗？此操作将清除所有地图元素，不可撤销。')) {
            this.saveHistory();
            
            this.mapData = {
                obstacles: [],
                spawnPoints: [],
                respawnPoints: [],
                specialPoints: [],
                bossPoints: []
            };
            
            this.render();
            this.updateStatus();
            this.showMessage('全屏已擦除', 'info');
        }
    }
    
    // 返回上一页
    goBack() {
        if (confirm('确定要返回吗？未保存的更改将丢失。')) {
            window.history.back();
        }
    }
    
    // 更新地图大小
    updateMapSize() {
        // 检查地图大小是否在游戏支持范围内
        const minSize = 600;
        const maxSize = 2400;
        
        if (this.state.mapWidth < minSize || this.state.mapWidth > maxSize ||
            this.state.mapHeight < minSize || this.state.mapHeight > maxSize) {
            this.showMessage(`地图大小必须在${minSize}-${maxSize}之间`, 'warning');
            return;
        }
        
        this.render();
        this.updateStatus();
    }
    
    // 显示消息
    showMessage(message, type = 'info') {
        // 创建消息元素
        const messageEl = document.createElement('div');
        messageEl.className = `alert alert-${type}`;
        messageEl.textContent = message;
        messageEl.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            border-radius: 8px;
            color: white;
            z-index: 1000;
            animation: slideIn 0.3s ease;
        `;
        
        const colors = {
            'success': '#27ae60',
            'warning': '#f39c12',
            'error': '#e74c3c',
            'info': '#3498db'
        };
        
        messageEl.style.background = colors[type] || '#3498db';
        
        document.body.appendChild(messageEl);
        
        // 3秒后自动移除
        setTimeout(() => {
            messageEl.style.animation = 'slideOut 0.3s ease';
            setTimeout(() => {
                if (messageEl.parentNode) {
                    messageEl.parentNode.removeChild(messageEl);
                }
            }, 300);
        }, 3000);
    }
}

// 页面加载完成后初始化编辑器
document.addEventListener('DOMContentLoaded', function() {
    window.mapEditor = new MapEditor();
});

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
    
    @keyframes slideOut {
        from { transform: translateX(0); opacity: 1; }
        to { transform: translateX(100%); opacity: 0; }
    }
`;
document.head.appendChild(style);